// 封装grapesjs的初始化逻辑
import "grapesjs/dist/css/grapes.min.css";
import { addPanelsButton } from "./addPanelsButton";
import zh from 'grapesjs/locale/zh';
import en from 'grapesjs/locale/en';
import grapesjs from "grapesjs";

// import Quill from 'quill';

// 清理旧的存储数据
// const clearLocalStorage = () => {
//   localStorage.removeItem("gjs-components");
//   localStorage.removeItem("gjs-styles");
//   localStorage.removeItem("gjs-html");
//   localStorage.removeItem("gjs-css");
// };

export const initializeGrapesJS = (
    containerId, blocks, pages
) => {
    //   clearLocalStorage(); // 清理旧的存储数据
    const customType = (editor) => {
        editor.I18n.addMessages({
            en: {
                styleManager: {
                    properties: {
                        // The key is the property name (or id)
                        'float': '浮动',
                        "display": '显示',
                        "position": '位置',
                        "top": '顶部',
                        "right": '右侧',
                        "left": '左侧',
                        "bottom": '底部',
                        "flex-direction": '布局方向',
                        "flex-wrap": '布局宽度',
                        "justify-content": '水平布局',
                        "align-items": '垂直布局',
                        "align-content": '所有行垂直布局',
                        "align-self": '侧轴对齐方式',
                        "width": '宽',
                        "height": '高',
                        "max-width": '最大宽度',
                        "min-height": '最小高度',
                        "margin": '外边距',
                        "padding": '内边距',
                        "font-family": '字体样式',
                        "font-size": '字体大小',
                        "font-weight": '字体比重',
                        "letter-spacing": '字符间距',
                        "color": '颜色',
                        "line-height": '行高',
                        "text-align": '字体水平布局',
                        "text-shadow": '字体阴影',
                        "background-color": '背景颜色',
                        "border-radius": '边框半径',
                        "border": '边框',
                        "box-shadow": '阴影',
                        "background": '背景',
                        "opacity": '不透明度',
                        "z-index": '层级',
                        "transition": '转变',
                        "perspective": '透视度',
                        "transform": '变换'
                    },
                }
            }
        });
        editor.StyleManager.addType('my-custom-prop', {
            // 自定义样式版ui
            create({ props, change }) {
                const el = document.createElement('div');
                el.innerHTML = `<input type="range" class="my-input" min="${props.min}" max="${props.max}"/>`;
                const inputEl = el.querySelector('.my-input');
                inputEl.addEventListener('change', event => change({ event })); //触发更新函数
                inputEl.addEventListener('input', event => change({ event, partial: true }));
                return el;
            },
            emit({ updateStyle }, { event, partial }) {
                const { value } = event.target;
                // 这里用的是百分比，设置高可能会没反应
                updateStyle(`${value}%`, { partial });
            },
            update({ value, el }) { el.querySelector('.my-input').value = parseInt(value, 10); },
            destroy() { },
        });
    };

// // 创建自定义富文本编辑器
// const customRichTextEditor = {
//     init: (editor, opts) => {
//       // 创建Quill编辑器容器
//       const editorContainer = document.createElement('div');
//       editorContainer.classList.add('quill-editor');
//       document.body.appendChild(editorContainer); // 将容器添加到页面中
  
//       // 初始化Quill编辑器
//       const quill = new Quill(editorContainer, {
//         theme: 'snow',
//         modules: {
//           toolbar: [
//             [{ 'header': [1, 2, false] }],
//             ['bold', 'italic', 'underline'],
//             [{ 'list': 'ordered'}, { 'list': 'bullet' }],
//             [{ 'script': 'sub'}, { 'script': 'super' }],
//             [{ 'indent': '-1'}, { 'indent': '+1' }],
//             [{ 'direction': 'rtl' }],
//             [{ 'size': ['small', false, 'large', 'huge'] }],
//             [{ 'color': [] }, { 'background': [] }],
//             [{ 'font': [] }],
//             [{ 'align': [] }],
//             ['link', 'image']
//           ]
//         }
//       });
  
//       // 返回Quill编辑器实例的方法
//       const getContent = () => quill.root.innerHTML;
//       const setContent = (content) => quill.root.innerHTML = content;
  
//       return { getContent, setContent };
//     }
//   };

    // 初始化
    let editor = grapesjs.init({
        // 绑定id对应的组件/标签
        
        container: `#${containerId}`,
        fromElement: true,
        height: '100vh',
        width: "auto",
        // plugins: [customType,ck],
        plugins: [customType],
        allowScripts: 1,
        // 存储管理器
        storageManager: {
            // id: 'gjs-',
            // type: 'local',
            autoload: 0
            // autosave: true,
            // storeComponents: true,
            // storeStyles: true,
            // storeHtml: true,
            // storeCss: true,
        },
        //   页面管理器
        pageManager: {
            pages: pages
        },
        // 国际化语言设置
        i18n: {
            messages: { zh, en },
        },
        // 选择器管理器-允许在项目中的所有组件中重用样式
        selectorManager: {
            componentFirst: true,
        },
        // 样式管理器
        styleManager: {
            sectors: [{
                name: "General",
                open: false,
                buildProps: [
                    "float",
                    "display",
                    "position",
                    "top",
                    "right",
                    "left",
                    "bottom",
                ],
            },
            {
                name: "Flex",
                open: false,
                buildProps: [
                    "flex-direction",
                    "flex-wrap",
                    "justify-content",
                    "align-items",
                    "align-content",
                    "order",
                    "flex-basis",
                    "flex-grow",
                    "flex-shrink",
                    "align-self",
                ],
            },
            {
                name: "Dimension",
                open: false,
                buildProps: [
                    "width",
                    "height",
                    "max-width",
                    "min-height",
                    "margin",
                    "padding",
                ],
            },
            {
                name: "Typography",
                open: false,
                buildProps: [
                    "font-family",
                    "font-size",
                    "font-weight",
                    "letter-spacing",
                    "color",
                    "line-height",
                    "text-align",
                    "text-shadow",
                ],
            },
            {
                name: "Decorations",
                open: false,
                buildProps: [
                    "border-radius-c",
                    "background-color",
                    "border-radius",
                    "border",
                    "box-shadow",
                    "background",
                ],
            },
            {
                name: "Extra",
                open: false,
                buildProps: ["opacity", "z-index", "transition", "perspective", "transform"],
            },
            {
                name: '设置组件宽(%)',
                open: false,
                properties: [{
                    type: 'my-custom-prop',
                    property: '宽度',
                    default: '50',
                    min: 1,
                    max: 100,
                },],
            },
            {
                name: '设置组件高(%)',
                open: false,
                properties: [{
                    type: 'my-custom-prop',
                    property: '高度',
                    default: '50',
                    min: 1,
                    max: 100,
                },],
            },
            ],
        },
        // 区块管理器(组件存放区域)
        blockManager: {
            // 绑定id对应的组件/标签
            appendTo: `#${blocks}`,
        }
    });





    // 设置滚动条的样式
    editor.addStyle(`
        /* 滚动条整体样式 */  
        ::-webkit-scrollbar {  
            width: 10px;             /* 滚动条的宽度 */  
            height: 13px;            /* 对于水平滚动条，设置其高度 */  
        }  
        
        /* 滚动条滑块 */  
        ::-webkit-scrollbar-thumb {  
            background-color: #bfbfbf; /* 滑块的颜色 */  
            border-radius: 10px;       /* 滑块的边角圆滑度 */  
            border: 2px solid transparent; /* 滑块边框，设置为透明时，边框不会显示 */  
            background-clip: content-box; /* 背景裁剪，确保边框不影响滑块大小 */  
        }  
        
        ::-webkit-scrollbar-thumb:hover{
            background: #a1a1a1;
        }

        ::-webkit-scrollbar-thumb:active {
                background-color: #a1a1a1;
        }

        /* 滚动条轨道 */  
        ::-webkit-scrollbar-track {  
            background: #f1f1f1; /* 轨道的颜色 */    
        }  
            ::-webkit-scrollbar-button:single-button {
                background-color: rgb(241, 241, 241);
                display: block;
                background-size: 10px;
                background-repeat: no-repeat;
            }

            ::-webkit-scrollbar-button:single-button:vertical:decrement {
                height: 10px;
                width: 10px;
                background-position: center 4px;
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(193, 193, 193)'><polygon points='50,00 0,50 100,50'/></svg>");
            }

            ::-webkit-scrollbar-button:single-button:vertical:decrement:hover {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(168, 168, 168)'><polygon points='50,00 0,50 100,50'/></svg>");
            }

            ::-webkit-scrollbar-button:single-button:vertical:decrement:active {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(120, 120, 120)'><polygon points='50,00 0,50 100,50'/></svg>");
            }

            ::-webkit-scrollbar-button:single-button:vertical:increment {
                height: 10px;
                width: 10px;
                background-position: center 2px;
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(193, 193, 193)'><polygon points='0,0 100,0 50,50'/></svg>");
            }

            ::-webkit-scrollbar-button:single-button:vertical:increment:hover {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(168, 168, 168)'><polygon points='0,0 100,0 50,50'/></svg>");
            }

            ::-webkit-scrollbar-button:single-button:vertical:increment:active {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(120, 120, 120)'><polygon points='0,0 100,0 50,50'/></svg>");
            }
                ::-webkit-scrollbar-button:single-button:horizontal:decrement {
                height: 10px;
                width: 10px;
                background-position: 3px 3px;
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(193, 193, 193)'><polygon points='0,50 50,100 50,0'/></svg>");
                }

                ::-webkit-scrollbar-button:single-button:horizontal:decrement:hover {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(168, 168, 168)'><polygon points='0,50 50,100 50,0'/></svg>");
                }

                ::-webkit-scrollbar-button:single-button:horizontal:decrement:active {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(120, 120, 120)'><polygon points='0,50 50,100 50,0'/></svg>");
                }

                ::-webkit-scrollbar-button:single-button:horizontal:increment {
                height: 10px;
                width: 10px;
                background-position: 3px 3px;
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(193, 193, 193)'><polygon points='0,0 0,100 50,50'/></svg>");
                }

                ::-webkit-scrollbar-button:single-button:horizontal:increment:hover {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(168, 168, 168)'><polygon points='0,0 0,100 50,50'/></svg>");
                }

                ::-webkit-scrollbar-button:single-button:horizontal:increment:active {
                background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='rgb(120, 120, 120)'><polygon points='0,0 0,100 50,50'/></svg>");
                }`)

    // 设置编辑器面板按钮
    addPanelsButton(editor);

    const excludedFiles = [
        "/blocks/other/addTest.js" // 排除other文件夹下的addTest.js
    ];
    
    const contexts = [
        require.context('../blocks/basic', false, /\.js$/), // 基本组件的BlockManager
        require.context('../blocks/column', false, /\.js$/), // 栏目类的BlockManager
        require.context('../blocks/homePage', false, /\.js$/), // 首页组件的BlockManager
        require.context('../blocks/producePage', false, /\.js$/), // 产品中心组件的BlockManager
        require.context('../blocks/module', false, /\.js$/), // 组件类的BlockManager
        require.context('../blocks/news', false, /\.js$/), // 新闻组件的BlockManager
        require.context('../blocks/picture', false, /\.js$/), // 输入图片类的BlockManager
        require.context('../blocks/serviceCenter', false, /\.js$/), // 服务中心类的BlockManager
        require.context('../blocks/card', false, /\.js$/), // 卡片类的BlockManager
        require.context('../blocks/other', false, /\.js$/) // 输入其他类的BlockManager
    ];
    
    contexts.forEach((context) => {
        context.keys().forEach((file) => {
            // 使用 require.context 提供的路径前缀
            const filePath = context.resolve(file);
            
            // 检查文件路径是否包含排除的模式
            const shouldExclude = excludedFiles.some(pattern => Array.from(filePath).includes(pattern));
            
            // 检查文件是否在排除列表中
            if (!shouldExclude) {
                try {
                    const module = context(file);
                    const moduleName = Object.keys(module)[0];
                    module[moduleName](editor);
                } catch (error) {
                    console.error("报错文件为",file);
                    console.error("报错信息为",error);
                }
            }
        });
    });
    return { editor };
};